package com.changgou.web.gateway.filter;

import com.changgou.web.gateway.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    public static final String Authorization = "Authorization";
    @Autowired
    private AuthService authService;

    @Value("${LoginUrl}")
    private  String LoginUrl;
    /**
     * Process the Web request and (optionally) delegate to the next {@code WebFilter}
     * through the given {@link GatewayFilterChain}.
     *
     * @param exchange the current server exchange
     * @param chain    provides a way to delegate to the next filter
     * @return {@code Mono<Void>} to indicate when request processing is complete
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取当前请求对象
        ServerHttpRequest request = exchange.getRequest();
        //判断是否登录，登录放行
        if(!URLFilter.hasAuthorize(request.getURI().getPath())){
            //放行
            return chain.filter(exchange);
        }
        //判断cookie中是否携带jti，未携带直接拒绝访问
        String jti = authService.getJtiFromCookie(request);
        if(StringUtils.isEmpty(jti)){
            /*response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();*/

            return this.toLoginPage(LoginUrl,exchange);
        }
        //3.从redis中获取jwt的值,如果该值不存在,拒绝本次访问
        String jwt = authService.getJwtFromRedis(jti);
        if (StringUtils.isEmpty(jwt)){
            //拒绝访问
            /*response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();*/
            return this.toLoginPage(LoginUrl,exchange);
        }

        //对当前的请求对象进行增强,让它会携带令牌的信息
        request.mutate().header(Authorization,"Bearer "+jwt);
        return chain.filter(exchange);
    }

    public Mono<Void> toLoginPage(String loginUrl,ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        response.setStatusCode(HttpStatus.SEE_OTHER);
        response.getHeaders().set("Location",loginUrl+"?FROM="+request.getURI());
        return response.setComplete();
    }

    @Override
    public int getOrder() {

        return 0;
    }
}
